<template>
  <div class="teacher-add">
    <el-page-header @back="$goBack" :content="pageTitle" />
    <el-form :model="form" :rules="rules" ref="formRef" v-loading="loading" @submit.prevent.native>
      <el-form-item label="头像" prop="avatar">
        <xu-upload v-model="form.avatar" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input maxlength="10" v-model="form.name" show-word-limit placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="座右铭" prop="slogan">
        <el-input type="textarea" maxlength="50" v-model="form.slogan" show-word-limit placeholder="请输入座右铭" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import XuUpload from '@/components/xu-upload'
import { mapActions } from 'vuex'
import { TeacherActionsEnum } from '../../../_/vue/store/teacher'
export default {
  components: { XuUpload },
  data () {
    return {
      id: '',
      loading: false,
      pageTitle: '添加讲师',
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        slogan: [{ required: true, message: '座右铭不能为空', trigger: 'blur' }]
      },
      form: {
        avatar: '',
        name: '',
        slogan: ''
      }
    }
  },
  mounted () {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.pageTitle = '编辑讲师'
      this.detail(this.id).then(response => {
        this.form = response.data
      })
    }
  },
  methods: {
    ...mapActions({
      detail: TeacherActionsEnum.EDIT,
      save: TeacherActionsEnum.SAVE,
      store: TeacherActionsEnum.STORE
    }),
    // 提交
    handleSubmit () {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            if (this.id) {
              await this.save({ id: this.id, data: this.form })
            } else {
              await this.store(this.form)
            }
            this.$message.success('操作成功')
            this.$goBack()
          } catch (err) {}
          this.loading = false
        }
        return false
      })
    }
  }
}
</script>
